import axios from 'axios'
import { ElMessage } from 'element-plus'
import store from '@/store'
import router from '@/router'

// 创建axios实例
const request = axios.create({
  baseURL: 'http://localhost:5000/api',
  timeout: 120000, // 增加到2分钟，适应AI分析需要
  withCredentials: false
})

// 请求拦截器
request.interceptors.request.use(
  config => {
    console.log(`[API Request] ${config.method?.toUpperCase()} ${config.url}`, config)
    
    const token = store.state.token
    if (token) {
      config.headers.Authorization = `Bearer ${token}`
      console.log('[API] Token attached:', token.substring(0, 20) + '...')
    } else {
      console.log('[API] No token found')
    }
    
    // 确保Content-Type正确设置
    if (config.method === 'post' || config.method === 'put') {
      config.headers['Content-Type'] = 'application/json'
    }
    

    
    return config
  },
  error => {
    console.error('[API] 请求拦截器错误:', error)
    return Promise.reject(error)
  }
)

// 响应拦截器
request.interceptors.response.use(
  response => {
    console.log(`[API Response] ${response.config.method?.toUpperCase()} ${response.config.url}`, response.data)
    return response
  },
  error => {
    console.error('[API] 响应拦截器错误:', error)
    
    if (error.response) {
      console.error('[API] 错误响应:', error.response.status, error.response.data)
      
      if (error.response.status === 401) {
        console.log('[API] 认证失败，清除token并跳转到登录页')
        store.dispatch('logout')
        router.push('/login')
        ElMessage.error('登录已过期，请重新登录')
      } else if (error.response.status === 403) {
        ElMessage.error('权限不足')
      } else if (error.response.status === 404) {
        ElMessage.error('请求的资源不存在')
      } else if (error.response.status >= 500) {
        ElMessage.error('服务器错误，请稍后重试')
      } else {
        ElMessage.error(error.response.data?.error || '请求失败')
      }
    } else if (error.code === 'ERR_NETWORK') {
      console.error('[API] 网络错误:', error.message)
      ElMessage.error('网络连接失败，请检查网络连接或服务器状态')
    } else if (error.code === 'ECONNABORTED') {
      console.error('[API] 请求超时')
      ElMessage.error('请求超时，请稍后重试')
    } else {
      console.error('[API] 未知错误:', error)
      ElMessage.error('未知错误，请稍后重试')
    }
    
    return Promise.reject(error)
  }
)



// API接口
const api = {
  auth: {
    login: (data) => request.post('/auth/login', data),
    init: () => request.post('/auth/init'),
    profile: () => request.get('/auth/profile')
  },
  
  lottery: {
    getList: (params) => request.get('/lottery/list', { params }),
    update: () => request.post('/lottery/update', {}),
    getStatistics: () => request.get('/lottery/statistics'),
    getRange: () => request.get('/lottery/range')
  },
  
  ai: {
    analyze: (data) => request.post('/ai/analyze', data),
    verify: (data) => request.post('/ai/verify', data),
    getPredictions: (params) => request.get('/ai/predictions', { params }),
    mutualExclusion: (data) => request.post('/ai/mutual-exclusion', data)
  },
  
  reports: {
    getSummary: () => request.get('/reports/summary'),
    getWinningAnalysis: () => request.get('/reports/winning-analysis'),
    getPredictionTrends: () => request.get('/reports/prediction-trends'),
    getReport: (type) => {
      const endpoints = {
        'summary': '/reports/summary',
        'winning-analysis': '/reports/winning-analysis',
        'prediction-trends': '/reports/prediction-trends'
      }
      return request.get(endpoints[type] || '/reports/summary')
    }
  }
}

export default api 